#include "../include/head.h"

//将用户信息从文件读取到链表
UserList *read_user_from_file() {
    UserList *list = create_user_list();
    FILE *file = fopen(USER_FILE, "r");
    if (file == NULL) {
        perror("无法打开用户信息文件");
        return list;
    }

    User user;
    while (fscanf(file, "%s %s", user.username, user.password) == 2) {
        add_user(list, user);
    }

    fclose(file);
    return list;
}

//将用户信息写入文件
void write_user_to_file(UserList *list) {
    FILE *file = fopen(USER_FILE, "w");
    if (file == NULL) {
        perror("无法打开用户信息文件");
        return;
    }

    UserNode *current = list->head;
    while (current != NULL) {
        fprintf(file, "%s %s\n", current->user.username, current->user.password);
        current = current->next;
    }

    fclose(file);
}

//将商品信息从文件读取到链表
CommodityList *read_commodity_from_file()
{
    CommodityList *list = create_commodity_list();
    FILE *file = fopen(COMMODITIES_FILE, "r");
    if (file == NULL) {
        perror("无法打开商品信息文件");
        return list;
    }

    Commodity commodity;
    while (fscanf(file, "%s %s %f %d", commodity.id, commodity.name, &commodity.price, &commodity.stock) == 4) {
        add_commodity(list, commodity);
    }

    fclose(file);
    return list;
}

//将商品信息写入文件
void write_commodity_to_file(CommodityList *list)
{
    FILE *file = fopen(COMMODITIES_FILE, "w");
    if (file == NULL) {
        perror("无法打开商品信息文件");
        return;
    }

    CommodityNode *current = list->head;
    while (current != NULL) {
        fprintf(file, "%s %s %.2f %d\n", current->commodity.id, current->commodity.name, current->commodity.price, current->commodity.stock);
        current = current->next;
    }

    fclose(file);
}

//将购物车的商品信息从文件读取到链表
CommodityList *read_shopping_cart_from_file()
{
    char filename[100];
    snprintf(filename, sizeof(filename), "./Commodity_management/data/%s.txt", username);
    CommodityList *list = create_shopping_cart_list();
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("无法打开购物车清单文件");
        return list;
    }

    Commodity commodity;
    while (fscanf(file, "%s %s %f %d", commodity.id, commodity.name, &commodity.price, &commodity.stock) == 4) {
        add_shopping_cart_commodity(list, commodity);
    }

    fclose(file);
    return list;
}
//yes
//将购物车的商品信息写入文件
void write_shopping_cart_to_file(CommodityList *list)
{
    char filename[100];
    snprintf(filename, sizeof(filename), "./Commodity_management/data/%s.txt", username);
    FILE *file = fopen(filename, "w");
    if (file == NULL) {
        perror("无法打开购物车清单文件");
        return;
    }

    CommodityNode *current = list->head;
    while (current != NULL) {
        fprintf(file, "%s %s %.2f %d\n", current->commodity.id, current->commodity.name, current->commodity.price, current->commodity.stock);
        current = current->next;
    }

    fclose(file);
}